package com.imad.mailservice;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailServerConfig {
	private String fromAddress;
	private String username;
	private String password;
	private String host;
	private String port;
	
	public MailServerConfig(String fromAddress, String username, String password, String host, String port) {
		this.fromAddress = fromAddress;
		this.username = username;
		this.password = password;
		this.host = host;
		this.port = port;
	}
	
	public Message getMessage() throws AddressException, MessagingException {
		Message message = new MimeMessage(getMailSession());
		message.setFrom(new InternetAddress(fromAddress));
		return message;
	} 
	
	
	private Properties getServerProperties(){
		Properties prop = new Properties();
		prop.setProperty("mail.smtp.host", host);
		prop.setProperty("mail.smtp.port", port);
		prop.setProperty("mail.smtp.auth", "true");
		return prop;
	}
	
	private Authenticator getAuth() {
		Authenticator auth = new Authenticator() {
			@Override
	        protected PasswordAuthentication getPasswordAuthentication() {
	                return new PasswordAuthentication(username, password);
	        }
		};
		return auth;
	}
	
	private Session getMailSession() {
		Session session = Session.getDefaultInstance(getServerProperties(), getAuth());
		return session;
	}
}
